package middol.base

import grails.converters.JSON
import grails.plugin.springsecurity.SpringSecurityService
import grails.util.Holders
import middol.logs.AuditLog
import middol.utils.SecurityUtils
import org.grails.web.servlet.mvc.GrailsWebRequest
import static grails.async.Promises.task

/**
* @Description:    操作日志记录
* @Author:         zhangjiayu@middol.com
* @CreateDate:     2020/8/5 13:23
* @Version:        1.0
*/
class AuditLogService {
    /**
     * 保存操作日志
     * @param type      操作类型：增删改
     * @param jsonData  操作的实体
     */
    def saveAuditLog(String type, def entry) {
        String className = entry?.class?.getName()
        def id = entry?.id
        if(!className.contains("AuditLog") && !className.contains("LoginRecord") && !className.contains("Requestmap") && id){
            //获取请求的路径
            GrailsWebRequest request = GrailsWebRequest.lookup()
            def uri = request?.request?.requestURI
            //获取当前登录人
            SpringSecurityService springSecurityService = Holders.grailsApplication.mainContext.getBean(SpringSecurityService.class)
            def currentUsername = springSecurityService.getPrincipal()?.getUsername()
            JSON jsonData = entry as JSON
            task{
                AuditLog.withTransaction { session->
                    def auditlog = [
                            operator: currentUsername ?: 'SYS',
                            className: className,
                            persistedObjectId: id,
                            eventName: type,
                            uri: uri,
                            jsonValue: "${jsonData}"
                    ]

                    new AuditLog(auditlog).save(flush: true)
                }
            }
        }
    }
}
